package com.itheima.notify.service;

import com.itheima.common.entity.NotifyMessage;
import com.itheima.common.exception.NcException;
import com.itheima.common.exception.enums.ResponseEnum;
import com.itheima.notify.util.JPushManager;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NotifyMessageService {

    @Autowired
    private JPushManager jPushManager;

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 向目标APP员工推送通知消息,并且将推送记录存储到MongoDB中
     * @param message
     */
    public void sendPushMsgByAlias(NotifyMessage message) throws Exception {
        //1.根据注册到极光平台的用户别名进行推送
        jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), message.getParameters());
        //TODO 将推送记录存入MongoDB
        mongoTemplate.save(message, "notifyMessage");
    }

    public List<NotifyMessage> queryNotifyMessage(String id, String type, String sponsor, String receiver) {
        //申请者 接收者 必须有一个有值
        if(StringUtils.isBlank(sponsor) && StringUtils.isBlank(receiver)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Query query = new Query();
        if (id != null) {
            //根据唯一标识
            query.addCriteria(Criteria.where("_id").is(new ObjectId(id)));
        }
        if (StringUtils.isNotBlank(type)) {
            //推送消息类型
            query.addCriteria(Criteria.where("messageType").is(type));
        }
        if (StringUtils.isNotBlank(sponsor)) {
            //发起方
            Criteria criteria = Criteria.where("applyUserId").is(Long.valueOf(sponsor));
            query.addCriteria(new Criteria().orOperator(criteria));
        }
        if (StringUtils.isNotBlank(receiver)) {
            //接收方
            Criteria criteria1 = Criteria.where("targets").in(receiver);
            Criteria criteria2 = Criteria.where("approveUserId").is(Long.valueOf(receiver));
            query.addCriteria(new Criteria().orOperator(criteria1, criteria2));
        }
        //根据创建时间倒序排序
        query.with(Sort.by(Sort.Order.desc("createTime")));

        List<NotifyMessage> notifyMessageList = mongoTemplate.find(query, NotifyMessage.class, "notifyMessage");
        return notifyMessageList;
    }
}
